const http = require('http');
const querystring = require('querystring');
const fs = require('fs');
const path = require('path');
const NodeRSA = require('node-rsa');

const server = http.createServer((req, res) => {
    const { method } = req;

    // 请求类型
    switch (method) {
        case "GET":
            get(req, res);
            break;
        case "POST":
            post(req, res);
            break;
        default:
            res.end();
            break;
    }
});

function get(req, res) {
    const [url, paramsStr] = req.url.split(/\?/);
    const params = querystring.parse(paramsStr);

    // 加载静态文件
    if (/\.(js|css)$/.test(url)) {
        res.end(fs.readFileSync(path.resolve(__dirname, `../public/${url}`), { encoding: 'utf-8' }));
        return;
    }

    // url
    switch (url) {
        case '/':
            const html = fs.readFileSync(path.resolve(__dirname, '../public/index.html'), { encoding: 'utf-8' });
            res.end(html);
            break;

        default:
            res.statusCode = 403;
            res.end();
            break;
    }
}

function post(req, res) {
    const { url } = req;

    // 接收 POST 的数据
    let postData = '';
    req.on('data', chunk => {
        postData += chunk;
    });

    req.on('end', () => {
        if (postData) {
            const params = JSON.parse(postData)

            switch (url) {
                case '/login':
                    let { uname, pwd } = params;
                    console.log('uname', uname);
                    console.log('pwd', pwd);

                    // const privateKey = fs.readFileSync(path.resolve(__dirname,'../RSA密钥/rsa_1024_priv.pem'),{encoding: 'utf-8'});
                    const privateKey = fs.readFileSync(path.resolve(__dirname, '../rsa/rsa_1024_priv.pem'));
                    const nodersa = new NodeRSA(privateKey);

                    // 因为 jsencrypt 自身使用的是 pkcs1 加密方案, nodejs 需要修改成 pkcs1
                    nodersa.setOptions({ encryptionScheme: 'pkcs1' });
                    pwd = nodersa.decrypt(pwd, 'utf-8');
                    console.log('pwd', pwd);

                    res.setHeader('Content-type', 'application/json')
                    res.end(JSON.stringify({ uname, pwd }));
                    break;

                default:
                    res.statusCode = 403;
                    res.end();
                    break;
            }

        }
    });
}

server.listen(3000, () => {
    console.log('http://localhost:3000/');
    console.log('http://127.0.0.1:3000/');
})